<?php
/**
 * Created by PhpStorm.
 * User: *!N.J
 * Date: 2021/8/24
 * Time: 15:23
 * QQ:1467572213
 */

namespace app\admin\controller;

use library\Controller;
use think\facade\Request;
use think\facade\Session;
use think\Db;
use \app\admin\model\Withdrawal as Withdrawal_m;

/**
 * 提现管理
 * Class Withdrawal
 * @package app\admin\controller
 */
class Withdrawal extends Controller
{
    /**
     * 提现列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        date_default_timezone_set('America/Mexico_City');
        $this->title = '提现列表';
        $keyword = input('get.keyword/s','');
        $order_id = input('get.order_id/s','');
        $create_time = input('get.create_time/s','');
        $status = input('get.status/s','');
        
        
        $list = Withdrawal_m::index($keyword,$order_id,$create_time,$status);
        // var_dump($list)
        $page = $list->render();  //构造分页
        $this->assign('pages', $page);   //输出分页
        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * 同意提现
     * @auth true
     * @menu true
     */

    public function withdrawal_pass()
    {
        if (Request::isPost()){
            $id = Request::post('id');
            $type = Request::post('type');
            
            $confirm_info = Db::name('fd_withdrawal')->where('id', $id)->find();
            
            $user_info = Db::name('fd_user')->find($confirm_info['uid']);
            
            $money = $confirm_info['actual_money'];
            
            if($type == 1){
                $res = $this->flb_pay($money,$user_info,$confirm_info['order_id']);
                
                if($res['respCode'] == 'SUCCESS'){
                    // return ['code'=>1,'msg'=>'Success'];
                    $list = Db::name('fd_withdrawal')->where('id', $id)
                ->update(['status'=>1]);
                }else{
                    return ['code'=>0,'msg'=>'Error'];
                }
            }
            
            if($type == 2){
                $res = $this->qeapay_pay($money,$user_info,$confirm_info['order_id']);
                // var_dump($res);die;
                if($res['respCode'] == 'SUCCESS'){
                    // return ['code'=>1,'msg'=>'Success'];
                    $list = Db::name('fd_withdrawal')->where('id', $id)
                ->update(['status'=>1]);
                }else{
                    return ['code'=>0,'msg'=>'Error'];
                }
            }
            
            if($type == 4){
                $res = $this->payman($confirm_info['actual_money'],$user_info,$confirm_info['order_id'],$confirm_info['bank_code']);
                // var_dump($res);die;
                if($res['respCode'] == 'SUCCESS'){
                    // return ['code'=>1,'msg'=>'Success'];
                    $list = Db::name('fd_withdrawal')->where('id', $id)
                ->update(['status'=>1]);
                    return ['code'=>1,'msg'=>'success'];
                }else{
                    return ['code'=>0,'msg'=>'Error'];
                }
            }
            
            if($type == 5){
                $res = $this->showpay($confirm_info['actual_money'],$user_info,$confirm_info['order_id'],$confirm_info['bank_code']);
                // var_dump($res);die;
                if($res['respCode'] == 'SUCCESS'){
                    // return ['code'=>1,'msg'=>'Success'];
                    $list = Db::name('fd_withdrawal')->where('id', $id)
                ->update(['status'=>1]);
                    return ['code'=>1,'msg'=>'success'];
                }else{
                    return ['code'=>0,'msg'=>'Error'];
                }
            }
            
            if($type == 3){
                // $res = $this->qeapay_pay($money,$user_info,$confirm_info['order_id']);
                // var_dump($res);die;


              $list = Db::name('fd_withdrawal')->where('id', $id)->update(['status'=>1]);


            // $res = Withdrawal_m::withdrawal_pass($id);
            
            // if ($res == 'success'){
            if ($list){
                return ['code'=>1,'msg'=>'提交成功'];
            }else{
                return ['code'=>0,'msg'=>$res];
            }
        }
           
            if($type == 8){
                // if($confirm_info['bank_code']=='MXNSTP'){
                //     if(strlen($user_info['account_number'])!=18){
                //         return ['code'=>0,'msg'=>$res['stp账号不是18位']];
                //     }
                // }else{
                //     if(strlen($user_info['account_number'])!=16){
                //         return ['code'=>0,'msg'=>$res['账号不是16位']];
                //     }
                // }
                if(strlen($user_info['card_num'])<8 || strlen($user_info['card_num'])>11 ){
                    return ['code'=>0,'msg'=>'证件不是8-11位'];
                }
                $res = $this->wowpay2($money,$user_info,$confirm_info['order_id'],$confirm_info['bank_code']);
                if($res['respCode'] == 'SUCCESS'){
                    $list = Db::name('fd_withdrawal')->where('id', $id)
                ->update(['status'=>1,'df_type'=>'wowpay2']);
                    return ['code'=>1,'msg'=>'success'];
                }else{
                    return ['code'=>0,'msg'=>$res['errorMsg']];
                }
            }
            
            if($type == 9){
                // if($confirm_info['bank_code']=='MXNSTP'){
                //     if(strlen($user_info['account_number'])!=18){
                //         return ['code'=>0,'msg'=>$res['stp账号不是18位']];
                //     }
                // }else{
                //     if(strlen($user_info['account_number'])!=16){
                //         return ['code'=>0,'msg'=>$res['账号不是16位']];
                //     }
                // }
                if(strlen($user_info['card_num'])<8 || strlen($user_info['card_num'])>11 ){
                    return ['code'=>0,'msg'=>'证件不是8-11位'];
                }
                $res = $this->qeapay2($money,$user_info,$confirm_info['order_id'],$confirm_info['bank_code']);
                if($res['respCode'] == 'SUCCESS'){
                    $list = Db::name('fd_withdrawal')->where('id', $id)
                ->update(['status'=>1,'df_type'=>'qeapay2']);
                    return ['code'=>1,'msg'=>'success'];
                }else{
                    return ['code'=>0,'msg'=>$res['errorMsg']];
                }
            }
            
            if($type == 10){
                if(strlen($user_info['card_num'])<8 || strlen($user_info['card_num'])>11 ){
                    return ['code'=>0,'msg'=>'证件不是8-11位'];
                }
                $res = $this->lexmpay($money,$user_info,$confirm_info['order_id'],$confirm_info['bank_code']);
                if($res['respCode'] == 'SUCCESS'){
                    $list = Db::name('fd_withdrawal')->where('id', $id)
                ->update(['status'=>1,'df_type'=>'lexmpay']);
                    return ['code'=>1,'msg'=>'success'];
                }else{
                    return ['code'=>0,'msg'=>$res['errorMsg']];
                }
            }
        } 
    }
    
    public function showpay($money,$user_info,$order_sn,$bank_code){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = "970804888";
        $merchant_key = "OXX3ABNRTBZQEA0K2EV3WNPJYDYGSFXN";
        
        $url = "https://payment.lexmpay.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => $bank_code,
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['holder_name'],
            'transfer_amount' => $money,
            'back_url' => Request::domain().'/index/notify/txs_notify',
            'remark' => 'cci'
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        
        $result = json_decode($result,true);
        return $result;
        
    }
    
    public function payman($money,$user_info,$order_sn,$bank_code){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = "110009063";
        $merchant_key = "QJX8SEW20TQ0ZBBEG4FWNDDSZ83SMNUY";
        
        
        $url = "https://payment.qeapay.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => $bank_code,
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['holder_name'],
            'transfer_amount' => $money,
            'back_url' => Request::domain().'/index/notify/txs_notify',
            'remark' => 'cci'
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        
        $result = json_decode($result,true);
        return $result;
        
    }
    
    
    public function flb_pay($money,$user_info,$order_sn){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = "777805222";
        $merchant_key = "XLCCJ3SXNNBIBPWEJP5BJDAQYL4APDJ9";
        
        $url = "https://interface.wowpayglobal.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => 'gcash',
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['bank_name'],
            'transfer_amount' => $money
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        
        $result = json_decode($result,true);
        return $result;
        
    }
    
    function asc_sort($params = array())
    {
        if (!empty($params)) {
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }
    public function sign($signSource,$key) {
        if (!empty($key)) {
             $signSource = $signSource."&key=".$key;
        }
        // echo $signSource;die;
        return md5($signSource);
    }
    
    public function http_post_res($url,$data)
    {
        $ch = curl_init();    
        curl_setopt($ch,CURLOPT_URL,$url); //支付请求地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        $response=curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    /**
     * 拒绝提现
     * @auth true
     * @menu true
     */
    public function withdrawal_refuse()
    {
        if (Request::isPost()){
            $id = Request::post('id');
            $res = Withdrawal_m::withdrawal_refuse($id);
            switch ($res)
            {
                case 'success':
                    return ['code'=>1,'msg'=>'处理成功,款项已原路退回'];
                    break;
                case 'error':
                    return ['code'=>0,'msg'=>'处理失败'];
                    break;
                case 'error_status':
                    return ['code'=>0,'msg'=>'系统错误'];
                    break;
            }
        }
    }
    
    public function wowpay2($money,$user_info,$order_sn,$bank_code){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = \Env::get('wow.mch_id');
        $merchant_key = \Env::get('wow.secret');
        
        $url = "https://interface.wowpayglobal.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => $bank_code,
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['holder_name'],
            'back_url'=>Request::domain().'/index/notify/tx_wowpay2_notify',
            'transfer_amount' => $money,
            'receiver_telephone'=>$user_info['phone_number']
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        $result = json_decode($result,true);
        file_put_contents(__DIR__.'/../logs/发起代付wowpay2.log', date('Y-m-d H:i:s') . ': ' . var_export($data,true) . "\n\r", FILE_APPEND);
        file_put_contents(__DIR__.'/../logs/发起代付wowpay2.log', date('Y-m-d H:i:s') . ': ' . var_export($result,true) . "\n\r", FILE_APPEND);
        return $result;
        
    }
    
    public function qeapay2($money,$user_info,$order_sn,$bank_code){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = \Env::get('qe.mch_id');
        $merchant_key = \Env::get('qe.secret');
        
        $url = "https://payment.qeapay.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => $bank_code,
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['holder_name'],
            'back_url'=>Request::domain().'/index/notify/tx_qeapay2_notify',
            'transfer_amount' => $money,
            'receiver_telephone'=>$user_info['phone_number']
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        $result = json_decode($result,true);
        file_put_contents(__DIR__.'/../logs/发起代付qeapay2.log', date('Y-m-d H:i:s') . ': ' . var_export($data,true) . "\n\r", FILE_APPEND);
        file_put_contents(__DIR__.'/../logs/发起代付qeapay2.log', date('Y-m-d H:i:s') . ': ' . var_export($result,true) . "\n\r", FILE_APPEND);
        return $result;
        
    }
    
    
    public function lexmpay($money,$user_info,$order_sn,$bank_code){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = \Env::get('le.mch_id');
        $merchant_key = \Env::get('le.secret');
        
        $url = "https://payment.lexmpay.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => $bank_code,
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['holder_name'],
            'back_url'=>Request::domain().'/index/notify/tx_lexmpay_notify',
            'transfer_amount' => $money,
            'receiver_telephone'=>$user_info['phone_number'],
            'remark'=>$user_info['card_num'],
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        $result = json_decode($result,true);
        file_put_contents(__DIR__.'/../logs/发起代付lexmpay.log', date('Y-m-d H:i:s') . ': ' . var_export($data,true) . "\n\r", FILE_APPEND);
        file_put_contents(__DIR__.'/../logs/发起代付lexmpay.log', date('Y-m-d H:i:s') . ': ' . var_export($result,true) . "\n\r", FILE_APPEND);
        return $result;
        
    }
}